package com.maoye.ossp.biz.intent.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.hotent.base.core.util.string.StringUtil;
import com.hotent.base.db.api.IdGenerator;
import com.maoye.ossp.biz.contract.entity.LeaseAssociated;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.service.ILeaseAssContractService;
import com.maoye.ossp.biz.contract.service.ISelfAssociatedService;
import com.maoye.ossp.biz.contract.service.TemplateService;
import com.maoye.ossp.biz.contract.utils.ContractUtils;
import com.maoye.ossp.biz.contract.utils.JacksonUtils;
import com.maoye.ossp.biz.intent.entity.IntAssbaseitems;
import com.maoye.ossp.biz.intent.entity.IntAssbrands;
import com.maoye.ossp.biz.intent.entity.IntAssitems;
import com.maoye.ossp.biz.intent.entity.IntAssociated;
import com.maoye.ossp.biz.intent.entity.IntAssshops;
import com.maoye.ossp.biz.intent.entity.IntSelfStore;
import com.maoye.ossp.biz.intent.service.IIntAssociatedService;
import com.maoye.ossp.biz.intent.service.IIntLeaseociatedService;
import com.maoye.ossp.biz.intent.service.IIntSelfociatedService;
import com.maoye.ossp.biz.negotiation.entity.Assrecords;
import com.maoye.ossp.biz.negotiation.service.AssinfoService;
import com.maoye.ossp.biz.negotiation.service.AssrecordService;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.SysBaseFormat;
import com.maoye.ossp.sys.base.service.ICMCateService;
import com.maoye.ossp.sys.base.service.SysBaseFormatService;
import com.maoye.ossp.sys.base.service.SysBaseShopService;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
import com.maoye.sc.service.user.UserServiceImpl;

/**
 * 对象功能:联营合同意向（新签、续签、变更、反馈）  控制器类
 * 开发公司:MOI
 * 开发人员:yanghao
 * 创建时间:2014-02-20 14:50:38
 */

@Controller
@RequestMapping("biz/intent/intLeaseociated")
public class IntLeaseociatedController extends BaseController {
	
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private IIntAssociatedService intAssociatedService;
	
	@Resource
	private IContractService  contractServce;
	@Resource
	private AssrecordService assrecordService;
	@Resource
	IIntLeaseociatedService iIntLeaseociatedService;
	@Resource
	public IdGenerator idGenerator;
	@Resource
	ISelfAssociatedService iSelfAssociatedService;
	@Resource
	ILeaseAssContractService iLeaseAssociatedService;
	@Resource
	IIntSelfociatedService intSelfociatedServicei;
	@Resource
	SysBaseFormatService sysBaseFormatService;
	@Resource
	AssinfoService assinfoService;
	@Resource
	private UserServiceImpl  userServiceImpl;
	@Resource
	private TemplateService templateService;
	@Resource
	SysBaseShopService sysBaseShopService;
	@Resource
	private ICMCateService icmCateService;
	
	@RequestMapping(value = "list")
	public String list( IntAssociated intAssociated,Model mode, HttpServletRequest request) {
		QueryFilter queryFilter = getQuerFilter(request, intAssociated);
		queryFilter.addFilter("area", intAssociated.getArea(), QueryOP.EQUAL);
		queryFilter.addFilter("areaId", intAssociated.getAreaId(), QueryOP.EQUAL);
		queryFilter.addFilter("store", intAssociated.getStore(), QueryOP.EQUAL);
		queryFilter.addFilter("storeId", intAssociated.getStoreId(), QueryOP.EQUAL);
		queryFilter.addFilter("floor", intAssociated.getFloor(), QueryOP.EQUAL);
		queryFilter.addFilter("floorId", intAssociated.getFloorId(), QueryOP.EQUAL);
		queryFilter.addFilter("intentType", intAssociated.getIntentType(), QueryOP.EQUAL);
		queryFilter.addFilter("intentNo", intAssociated.getIntentNo(), QueryOP.EQUAL);
		queryFilter.addFilter("isContractModify", intAssociated.getIsContractModify(), QueryOP.EQUAL);
		String isModifyContract = intAssociated.getIsModifyContract();
		if("0".equals(intAssociated.getIsModifyContract())){
			isModifyContract = "";
		}
		queryFilter.addFilter("isModifyContract",isModifyContract , QueryOP.EQUAL);
		queryFilter.addFilter("isCreateContract", intAssociated.getIsCreateContract(), QueryOP.EQUAL);
		String createBy = null;
		if(StringUtil.isNotEmpty(intAssociated.getCreateBy())){
			createBy = ContractUtils.getUserId(intAssociated.getCreateBy());
		}
		User user=userServiceImpl.getUserById(UserUtils.getCurrentUserId().toString());
		String userType= user.getUserType();
		if(ContractUtils.USER_TYPE_S.equals(userType)){
			queryFilter.addFilter("supplierId",user.getId().toString(), QueryOP.EQUAL);
		}
		queryFilter.addFilter("createBy", createBy, QueryOP.EQUAL);
		queryFilter.addFilter("status", intAssociated.getStatus(), QueryOP.EQUAL);
		queryFilter.addFilter("startDate", intAssociated.getStartDate(), QueryOP.EQUAL);
		queryFilter.addFilter("contractType", ContractUtils.CONTRACT_TYPE_ZP, QueryOP.EQUAL);
		queryFilter.addFilter("endDate", intAssociated.getEndDate(), QueryOP.EQUAL);
		Page<IntAssociated> page =null;
		if(intAssociated.getIntAssbrandsList() !=null && !intAssociated.getIntAssbrandsList().isEmpty() ){
			IntAssbrands brand = intAssociated.getIntAssbrandsList().get(0);
			if(StringUtil.isNotEmpty(brand.getBrandCName())){
				queryFilter.addFilter("brandCName", intAssociated.getIntAssbrandsList().get(0).getBrandCName(), QueryOP.EQUAL);
				mode.addAttribute("brandCName", intAssociated.getIntAssbrandsList().get(0).getBrandCName());
				page = (Page<IntAssociated>) intAssociatedService.find1(queryFilter);
			}else{
				page = (Page<IntAssociated>) intAssociatedService.find(queryFilter);
			}
		}else{
			 page = (Page<IntAssociated>) intAssociatedService.find(queryFilter);
		}
		
		int totalSize = (page.getTotal() + page.getPageSize() - 1) / page.getPageSize();
		mode.addAttribute("page", page);
		mode.addAttribute("totalSize", totalSize);
		mode.addAttribute("intAssociated", intAssociated);
		return resultPage("/biz/intent/intLeaseociated/list", mode, request); 
	}
	/**
	 * 保存意向
	 * @param model
	 * @param intAssociated
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年5月28日
	 */
	@SuppressWarnings("serial")
	@RequestMapping(value = "save")
	public String save( Model model,IntAssociated intAssociated,RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response) throws Exception {
		intAssociatedService.save(intAssociated);
		Map<String, Object> map = new HashMap<String, Object>();
		Assrecords assrecords = assrecordService.get(intAssociated.getNegotiationId()) ;
		String navId = request.getParameter("navId");
		map.put("id", assrecords.getAssinfo().getId());
		map.put("status", ContractUtils.NEG_STATUS_YTJ);
		assinfoService.updateStatus(map);
		addMessage(redirectAttributes, "保存'" + intAssociated.getSubject()+ "意向合同'成功");
		return "redirect:/biz/intent/intLeaseociated/list?navId="+navId;
	}
	
	
	/**
	 * 保存意向
	 * @param model
	 * @param intAssociated
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年5月28日
	 */
	@RequestMapping(value = "submit")
	public String submit( Model model,IntAssociated intAssociated,RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response) throws Exception {
		String navId =request.getParameter("navId");
		intAssociatedService.submit(intAssociated);
		addMessage(redirectAttributes, "提交'" + intAssociated.getSubject()+ "意向合同'成功");
		return "redirect:/biz/intent/intLeaseociated/list?navId="+navId;
	}
	
	/**
	 * 跳转到新增联营合同意向页面 
	 * @param intAssociated
	 * @param request
	 * @param model
	 * @return
	 * @author yanghao
	 * @throws Exception 
	 * @data 2014年3月31日
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "{id}/add")

	public String add(@PathVariable Long id,IntAssociated intAssociated,HttpServletRequest request, Model model) throws Exception {

		model = intAssociatedService.init(id,model);
		return resultPage("/biz/intent/intLeaseociated/add", model, request);
	}

	@RequestMapping(value = "{id}/edit")
	public String edit(@PathVariable Long id, Model model,HttpServletRequest request) {
		model= intAssociatedService.edit(id,model);
		return resultPage("/biz/intent/intLeaseociated/add", model, request);
	}
	/**
	 * 批量删除意向合同
	 * @param ids
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @author yanghao
	 * @data 2014年5月22日
	 */
	@RequestMapping(value = "{ids}/removeBatch")
	public String removeBatch(@PathVariable String ids, HttpServletRequest request,Model model,RedirectAttributes redirectAttributes) {
		String navId = request.getParameter("navId");
		intAssociatedService.removeBatch(ids);
		redirectAttributes.addFlashAttribute(navId);
		return "redirect:/biz/intent/intLeaseociated/list?navId="+navId;
	}
	/**
	 * 展示意向合同详细信息
	 * @param id
	 * @param model
	 * @return
	 * @author yanghao
	 * @data 2014年5月23日
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "{id}/view")
	public String view(@PathVariable Long id,HttpServletRequest request, Model model) {
		IntAssociated intSelfociated = intAssociatedService.get(id);
		SysBaseFormat format = sysBaseFormatService.getFormatByCode(intSelfociated.getFormatId());
		
		StringBuilder shopName = new StringBuilder();
		List<IntAssshops>  assshopsList =  intSelfociated.getIntAssshopsList();
		List<IntSelfStore> selfStoreList = intSelfociated.getIntStoreList();
		StringBuilder stores =new StringBuilder();
		Long contractId =  intSelfociated.getContractId();
		if(contractId != null){
			LeaseAssociated associated = iLeaseAssociatedService.get(contractId.toString());
			if(associated!=null){
				associated.setVersionUrl("biz/intent/intLeaseociated/");
			}
			model.addAttribute("associated", associated);
		}
		if(assshopsList !=null && assshopsList.size()>0){
			for (int i = 0; i < assshopsList.size(); i++) {
				shopName.append(assshopsList.get(i).getShop());
				shopName.append(",");
			}
		}
		if(selfStoreList !=null && selfStoreList.size()>0){
			for (int i = 0; i < selfStoreList.size(); i++) {
				stores.append(selfStoreList.get(i).getStore());
				stores.append(",");
			}
		}
		User user=userServiceImpl.getUserById(UserUtils.getCurrentUserId().toString());
		model.addAttribute("userType", user.getUserType());
		if(user.getUserType().equals("SUPPLIER")){
			model.addAttribute("isShowDel", "false");
		}else{
			model.addAttribute("isShowDel", "true");
		}
		model.addAttribute("stores", stores);
		model.addAttribute("intAssociated", intSelfociated);
		model.addAttribute("format", format);
		model.addAttribute("shopName", shopName);
		
		return resultPage("/biz/intent/intLeaseociated/view", model, request);
	}
	/**
	 * 删除
	 * @param id
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @author yanghao 
	 * @data 2014年5月23日
	 */
	@RequestMapping(value = "{id}/delete")
	public String delete(@PathVariable Long id, Model model,
			RedirectAttributes redirectAttributes) {
		intAssociatedService.remove(id);
		addMessage(redirectAttributes, "删除合同作废意向成功！");
		return "redirect:/biz/intent/intAssociated/list";
	}
	
	/**
	 * 导入意向到合同信息
	 * @param model
	 * @return
	 * @author yangh
	 * @throws Exception 
	 * @data 2014年4月19日
	 */
	@RequestMapping(value = "{id}/insertToContract")
	public void insertToContract(@PathVariable Long id,Model model,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes) throws Exception{
			String navId = request.getParameter("navId");
			response.setCharacterEncoding("utf-8");
			PrintWriter out =  response.getWriter();
			StringBuilder sb = new StringBuilder();
			try {
				LeaseAssociated associatedContract = new LeaseAssociated();
				iIntLeaseociatedService.saveToContract(id,associatedContract);
				Map map = new HashMap();
				map.put("id", id);
				map.put("isCreateContract", ContractUtils.IS_CONTRACT_MODIFY_YES);
				intAssociatedService.updateIsCreateContract(map);//设置为已导入合同
				sb.append("{\"success\":true}");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				sb.append("{\"success\":false}");
			}
			out.write(sb.toString());
			out.flush();
			out.close();
	}
	/**
	 * 编辑意向结算及分成条款
	 * @param model
	 * @param request
	 * @param baseJson
	 * @param operate
	 * @param num
	 * @param redirectAttributes
	 * @return
	 * @author yanghao
	 * @data 2014年6月10日
	 */
	@RequestMapping(value = "editModalBase")
	public String editModalBase(Model model,HttpServletRequest request,String baseJson,String operate,String num,RedirectAttributes redirectAttributes){
		String _base=baseJson.replace("'", "\"").replace("@", "*").replace("#", "*");
		String contractType = request.getParameter("contractType");
		SimpleFilterProvider fp = new SimpleFilterProvider();
		fp.addFilter(
				"executeFilter",
				SimpleBeanPropertyFilter.serializeAllExcept(new String[] {
				 "createBy" }));
		IntAssbaseitems base =JacksonUtils.create().filter("myFilter", "id").json2Obj(_base, IntAssbaseitems[].class)[0];
		model.addAttribute("base", base);
		model.addAttribute("operate","edit");
		model.addAttribute("num",num);
		model.addAttribute("contractType", contractType);
		return "/biz/intent/intAssociated/modalBase";
	}
	/**
	 * 编辑（查看）意向合同条款
	 * @param model
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @author yanghao
	 * @data 2014年6月10日
	 */
	@RequestMapping(value = "editAssitems")
	public String editAssitems(Model model,String itemsJson,String operate,String num ,HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		String _items=itemsJson.replace("'", "\"");
		SimpleFilterProvider fp = new SimpleFilterProvider();
		fp.addFilter(
				"executeFilter",
				SimpleBeanPropertyFilter.serializeAllExcept(new String[] {
				 "createBy" }));
		IntAssitems items =JacksonUtils.create().filter("myFilter", "id").json2Obj(_items, IntAssitems[].class)[0];
		model.addAttribute("items", items);
		model.addAttribute("operate","edit");
		model.addAttribute("contractType", "leaseassociated");
		model.addAttribute("num",num);
		return "/biz/intent/common/modalitems";
	}
	/**
	 * 选择要创建的版本
	 * @param mainId
	 * @param historyId
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 * @author yanghao
	 * @data 2014年6月11日
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "{mainId}/{historyId}/{id}/getMainVersion")
	public String getMainVersion(@PathVariable String mainId,@PathVariable String historyId,@PathVariable Long id, HttpServletRequest request,Model model) {
		HashMap queryvalidate = new HashMap();
		String contractAttribute = request.getParameter("contractAttribute");
		String intAssociatedId = request.getParameter("intAssociatedId");
		queryvalidate.put("mainId", mainId);
		LeaseAssociated contract=iLeaseAssociatedService.getMainVersion(queryvalidate); 
		contract.setVersionUrl("biz/intent/intLeaseociated/");
		contract.setHistoryId(historyId);
		//创建“新版本”时，获取最新的版本信息返回verisonView.jsp页面
		model.addAttribute("version", contract);
		model.addAttribute("intAssociatedId", intAssociatedId);
		model.addAttribute("contractAttribute", contractAttribute);
		return resultPage("/biz/intent/common/versionModal",model,request);
	} 
	
	/**
	 * 
	 * @param id
	 * @param historyId
	 * @param intAssociatedId
	 * @param navId
	 * @param request
	 * @param response
	 * @param assistId
	 * @param model
	 * @return
	 * @throws Exception
	 * @author yanghao
	 * @data 2014年6月11日
	 */
	@RequestMapping(value = "{id}/{historyId}/{intAssociatedId}/createNewVersion")
	public void createNewVersion(@PathVariable String id,@PathVariable String historyId,@PathVariable Long intAssociatedId,String navId,HttpServletRequest request,HttpServletResponse response,
			String assistId, Model model) throws Exception{
			String contractOperate = request.getParameter("contractAttribute");
			response.setCharacterEncoding("utf-8");
			PrintWriter out =  response.getWriter();
			StringBuilder sb = new StringBuilder();
		//合同变更，续签，新签，先生号
		//合同基本信息
		try {
			LeaseAssociated associated = iLeaseAssociatedService.createNewVersion(id,assistId,historyId);
			iIntLeaseociatedService.saveToContract(intAssociatedId,associated);
			Map map = new HashMap();
			map.put("id", intAssociatedId);
			map.put("isCreateContract", ContractUtils.IS_CONTRACT_MODIFY_YES);
			intAssociatedService.updateIsCreateContract(map);//设置为已导入合同
			sb.append("{\"success\":true}");
		} catch (Exception e) {
			// TODO: handle exception
			sb.append("{\"success\":false}");
		}
		out.write(sb.toString());
		out.flush();
		out.close();
	}
	
	/**
	 *根據意向ID查看合同信息
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "getContarctByIntId")
	public String getContarctByIntId(Long id,HttpServletRequest request,Model model){
		String navId = request.getParameter("navId");
		LeaseAssociated associatedContract =iLeaseAssociatedService.getByIntId(id);
		return "redirect:/biz/contract/leaseassociated/"+associatedContract.getId()+"/view?navId="+navId;
	}
	
}
